package com.ssh.filter;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.ssh.model.User;
import com.ssh.service.IUserService;

@Component("accessFilter")
public class AccessFilter implements Filter {

	private IUserService userService;
	@Inject
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		User u = (User) req.getSession().getAttribute("loginUser");
		if(u == null){
			((HttpServletResponse)response).sendRedirect(req.getContextPath()+"/guoli/login");
		} else {
//			ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
//			IUserService userService = (IUserService) ac.getBean("userService");
			User user = userService.getUser(u.getId());
			if(user == null){
				((HttpServletResponse)response).sendRedirect(req.getContextPath()+"/guoli/login");
			}else{
				if(!user.getName().equals(u.getName())||!user.getPassword().equals(u.getPassword())){
					((HttpServletResponse)response).sendRedirect(req.getContextPath()+"/guoli/login");
				}
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
}
